import type { Ref } from 'vue'
import { nextTick, ref, watch } from 'vue'
import type { FormOptions } from '@/components/ui/form/src/types/type'

export function useModalForm(formRef: Ref<any>, options: Ref<FormOptions[]>, disabledEditOptions: string[]) {
  const visible = ref<boolean>(false)
  const type = ref<'add' | 'edit'>()
  const formModel = ref()
  const modalFormOptions = ref<FormOptions[]>([])
  const validatedForm = ref(false)

  function onClickAddModal() {
    visible.value = true
    type.value = 'add'
    nextTick(() => {
      formModel.value = formRef.value.model
    })
  }

  function onClickEditModal(data: Record<string, any>) {
    visible.value = true
    type.value = 'edit'
    nextTick(() => {
      formModel.value = formRef.value.model = data
    })
  }

  function onClickSubmitForm() {
    const validate = formRef.value.validate()
    validate()
      .then(() => {
        formModel.value = formRef.value.model
        validatedForm.value = true
      })
      .catch(() => {
        window.$message.error('The form is filled in incorrectly, please check')
      })
  }

  function onClickResetForm() {
    validatedForm.value = false
    formRef.value?.resetFields()
  }

  watch(() => visible.value, (val) => {
    if (!val)
      onClickResetForm()
  })

  // 处理编辑时有些选项不可修改
  watch([() => type.value, () => options.value], (val) => {
    if (val[0] === 'edit' && disabledEditOptions?.length) {
      const copyOptions = JSON.parse(JSON.stringify(options.value))
      modalFormOptions.value = copyOptions.map((item: any) => {
        if (disabledEditOptions.includes(item.prop))
          item.attrs.disabled = true

        return item
      })
    }
    else {
      modalFormOptions.value = options.value
    }
  })

  // 派发formModel方便外层动态处理表单
  watch(() => formRef.value?.model, (nVale: any) => {
    formModel.value = nVale
  }, { deep: true })

  return {
    visible,
    type,
    formModel,
    modalFormOptions,
    validatedForm,
    onClickAddModal,
    onClickEditModal,
    onClickSubmitForm,
    onClickResetForm,
  }
}
